var express = require('express');
var router = express.Router();

const fs = require('fs')
const path = require('path')
const formidable = require('formidable')

function objForEach(obj, fn) {
  let key, result
  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      result = fn.call(obj, key, obj[key])
      if (result === false) {
        break
      } 
    }
  }
}

// 保存上传的文件
function saveFiles(req) {
  return new Promise((resolve, reject) => {
    const imgLinks = []
    const form = new formidable.IncomingForm()
    form.parse(req, function (err, fields, files) {
      if (err) {
        reject('formidable, form.parse err', err.stack)
      }
      // 存储图片的文件夹
      const storePath = path.resolve(__dirname, '..', 'upload-files')
      if (!fs.existsSync(storePath)) {
        fs.mkdirSync(storePath)
      }

      // 遍历所有上传来的图片
      objForEach(files, (name, file) => {
        // 图片临时位置
        const tempFilePath = file.path
        // 图片名称和路径
        const fileName =  new Date().getTime() + file.name.split(" ").join()
        const fullFileName = path.join(storePath, fileName)
        // 将临时文件保存为正式文件
        fs.renameSync(tempFilePath, fullFileName)
        // 存储链接
          // url = "http://localhost:8080/api/getImg?name=";
        let url = "https://www.ourspark.org/api/getImg?name=";
        imgLinks.push(url + fileName)
      })

      // 返回结果
      resolve({
        errno: 0,
        data: imgLinks
      })
    })
  })
}
router.post('/', function (req, res, next) {
  // console.log("received imgs")

  // 获取数据
  saveFiles(req).then((data) => {
    // 返回结果
    res.end(JSON.stringify(data))
  }).catch((err) => {
    res.end(err)
  })



});

module.exports = router;
